package com.alorm.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alorm.core.exceptions.NotFoundType;
import com.test.bo.Etudiant;

public class AlormUtils {

	public static String getClassName(Class pClass) {

		String[] tokens = pClass.getName().trim().split("\\.");

		return tokens[tokens.length - 1];

	}

	public static String getPkName(Class pClass) {
		Field field = pClass.getDeclaredFields()[0];
		String fNom = field.getName();
		return fNom;
	}

	public static String getGetterMethod(String pFieldName) {

		char majChar = Character.toUpperCase(pFieldName.charAt(0));

		return "get" + majChar + pFieldName.substring(1);

	}

	public static String[] getAllFieldsName(Class pClass) {

		Field fields[] = pClass.getDeclaredFields();
		String fieldsName[] = new String[fields.length];

		for (int i = 0; i < fields.length; i++) {
			fieldsName[i] = fields[i].getName();
		}

		return fieldsName;
	}

	public static Map<String, String> getAllFieldsValue(Object pObject,
			List listClassPer) throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {

		Class lClass = pObject.getClass();
		Map<String, String> fieldsValue = new HashMap<String, String>();
		Field fields[] = lClass.getDeclaredFields();
		String fieldName;
		Class fieldClass;
		Method method = null;
		Object val = null;
		// number = (Number)

		for (int i = 1; i < fields.length; i++) {
			fieldName = fields[i].getName();
			fieldClass = fields[i].getType();

			if (!fieldClass.equals(ArrayList.class)) {

				method = lClass.getMethod(getGetterMethod(fieldName));
				val = method.invoke(pObject);

				if (!listClassPer.contains(fieldClass)) {
					if (val.getClass().equals(String.class))
						val = "'" + val + "'";

				} else {
					String pkName = getPkName(fieldClass);
					method = fieldClass.getMethod(getGetterMethod(pkName));
					if (val != null)
						val = method.invoke(val);

				}

				fieldsValue.put(fields[i].getName(), String.valueOf(val));

			}
		}

		return fieldsValue;
	}

	public static String getClassName(Type pType) {

		String[] tokens = pType.toString().trim().split("\\.");

		return tokens[tokens.length - 1];

	}

	public static String getClass(Type pType) {

		String[] tokens = pType.toString().trim().split(" ");

		return tokens[1];

	}

}
